﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

using FCNS.KeepMoney.Forms;
using FCNS.KeepMoney.Configuration;
using FCNS.KeepMoney.Data;
using FCNS.KeepMoney.Util;

using FCNS.Interfaces;
using FCNS.Utility;
using FCNS.Translation;

namespace FCNS.KeepMoney
{
    static class Program
    {
        public static bool OpenSoftByKMDfile = false;

        static List<IDataFormat> kmDataFormat = new List<IDataFormat>();
        public static List<IDataFormat> KMDataFormat
        {
            get { return kmDataFormat; 
            }
        }
        
        public static bool SaveKMD
        {
            set
            {
                mainform.toolMenuSave.Enabled = value;
            }
        }

        static ImageList imagesList;
        public static ImageList ImagesList
        {
            get { return imagesList; }
        }

        static Translate translation = new Translate();
        public static Translate Translation
        {
            get
            {
                return translation;
            }
        }

        private static AppConfigEx appConfig = AppSerializer.LoadConfig();
        public static AppConfigEx AppConfig
        {
            get { return appConfig; }
        }

        private static Forms.MainForm mainform = null;
        public static Forms.MainForm TheMainForm
        {
            get { return mainform; }
        }

        private static DateTime yearShown = DateTimeUtil.CalculateTheBillingDate(DateTime.Now.Year, DateTime.Now.Month);
        /// <summary>
        /// 获取 KMoney 当前数据的年份
        /// </summary>
        public static DateTime YearShown
        {
            get { return yearShown; }
            set { yearShown = value; }
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
                if (args.Length > 0)
                {
                    if (args[0].EndsWith(AppDefines.fileExt))//通过文件关联打开程序,参数为数据库文件完整路径
                    {
                        OpenSoftByKMDfile = true;
                        ProgramUtil.UpdateFileOpenRecord(args[0]);
                    }
                    else
                    {
                        LoadArgs(args);
                        return;
                    }
                }

                UpdateSoftware();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                InitImagesList();

                LoadTranslation();
                LoadKMDataFormat();

                if (appConfig.App.FileOpenRecords.Count == 0)
                    LoadedConfigurationFileForTheFirstTime();

                bool bRun = true;
                Mutex m = new Mutex(true, Application.ProductName, out   bRun);

                if (bRun)
                {
                    m.ReleaseMutex();
                    mainform = new Forms.MainForm();

                    ThreadPool.QueueUserWorkItem(CheckUpdate);
                    //try
                    //{
                    Application.Run(mainform);
                    //}
                    //catch (Exception error) { MessageBox.Show("Program.cs\r\n" + error.Message + "\r\n" + error.Source); }
                }
                else
                    mainform.Show();

                CleanUp();
        }

        private static void LoadArgs(string[] args)
        {
            string str = args[0];
            if (str.StartsWith("-"))
                str = str.Remove(0, 1);

            switch (str)
            {
                case "?":
                    ArgsUtil.ArgsHelp();
                    break;
                case "Compress":
                    ArgsUtil.ComFile(args[1]);
                    break;
                case "Decompress":
                    ArgsUtil.DecomFile(AppDefines.appPath + "update");
                    break;
                case "LanToLng":
                    break;
                case "LanToXml":
                    break;
                default:
                    MessageBox.Show("参数错误,请输入 keepmoney -? 查看列表");
                    break;
            }
        }

        private static void UpdateSoftware()
        {
            string updateDict = AppDefines.appPath + "update";
            if (!Directory.Exists(updateDict))
            {
                Directory.CreateDirectory(updateDict);
                return;
            }
            //if (!File.Exists(AppDefines.appPath + "updatesoft.exe"))
            //    BuildUpdateSoftExe();

            //foreach (string file in Directory.GetFiles(updateDict))
            //{
            //    if (file.EndsWith(".gz"))
            //    {
            //        System.Threading.Thread.Sleep(5000);
            //        System.Diagnostics.Process.Start(AppDefines.appPath + "updatesoft.exe");
            //        Application.Exit();
            //    }
            //}
            ////执行更新完成后要执行更新脚本
        }

        private static void CheckUpdate(object o)
        {
            List<UpdateComponentInfo> updateInfos = new List<UpdateComponentInfo>();
            updateInfos.Add(new UpdateComponentInfo("KeepMoney", StrUtil.GetVersion(AppDefines.version),
                AppDefines.VersionUrl, AppDefines.shortName));

            UpdateComponent up = new UpdateComponent(updateInfos, AppDefines.UpdateUrl, null);

            if (up.CheckIfUpdateIsAvailThenInstall())
                mainform.notifyIcon1.ShowBalloonTip(30000, "(*^◎^*)", "新版本已发布,请登陆官网下载更新", ToolTipIcon.Info);
        }

        private static void BuildUpdateSoftExe()
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();

            cp.OutputAssembly = AppDefines.appPath + "updatesoft.exe";
            cp.ReferencedAssemblies.Add("System.dll");

            cp.WarningLevel = 3;

            cp.GenerateExecutable = true;
            cp.GenerateInMemory = false;

            System.CodeDom.Compiler.TempFileCollection tfc = new TempFileCollection(Application.StartupPath, false);
            CompilerResults cr = new CompilerResults(tfc);

            cr = provider.CompileAssemblyFromSource(cp, Properties.Resources.UpdateSoftSource);

            if (cr.Errors.Count > 0)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder(LanguageUtil.升级程序生成出错  + "！！！\r\n\r\n");
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    sb.Append(ce.ToString() + "\r\n");

                MessageBox.Show(sb.ToString(), "-_-#");
            }

        }

        private static void InitImagesList()
        {
            imagesList = new ImageList();
            imagesList.Images.Add(Properties.Resources.folder32);
            imagesList.Images.Add(Properties.Resources.dollar12_32);
            imagesList.Images.Add(Properties.Resources.dollar2_32);
            imagesList.Images.Add(Properties.Resources.dollar3_32);
            imagesList.Images.Add(Properties.Resources.dollar4_32);
            imagesList.Images.Add(Properties.Resources.dollar5_32);
            imagesList.Images.Add(Properties.Resources.m1_32);
            imagesList.Images.Add(Properties.Resources.m2_32);
            imagesList.Images.Add(Properties.Resources.m32);
            imagesList.Images.Add(Properties.Resources.m4_32);
            imagesList.Images.Add(Properties.Resources.rmb1_32);
            imagesList.Images.Add(Properties.Resources.pig32);
            imagesList.Images.Add(Properties.Resources.pig1_32);
            imagesList.Images.Add(Properties.Resources.pig2_32);
            imagesList.Images.Add(Properties.Resources.cat1_32);
            imagesList.Images.Add(Properties.Resources.cat2_32);
            imagesList.Images.Add(Properties.Resources.cat3_32);
            imagesList.Images.Add(Properties.Resources.box1_32);
            imagesList.Images.Add(Properties.Resources.contact_32);
            imagesList.Images.Add(Properties.Resources.box3_32);
            imagesList.Images.Add(Properties.Resources.box4_32);
            imagesList.Images.Add(Properties.Resources.ba5_32);
            imagesList.Images.Add(Properties.Resources.ba6_32);
            imagesList.Images.Add(Properties.Resources.bag2_32);
            imagesList.Images.Add(Properties.Resources.bag3_32);
            imagesList.Images.Add(Properties.Resources.bag4_32);
            imagesList.Images.Add(Properties.Resources.house_32);
            imagesList.Images.Add(Properties.Resources.alert_32);
        }

        private static void LoadedConfigurationFileForTheFirstTime()
        {
            appConfig.MainForm.X = 49;
            appConfig.MainForm.Y = 69;
            appConfig.MainForm.Width = 780;
            appConfig.MainForm.Height = 548;

            appConfig.Money.ShowMinus = true;
            appConfig.Money.ShowPlus = true;
            //配置列
            appConfig.MainForm.ListViewEntryColumns.Clear();//如果首次打开软件却不建立数据库,下次打开就导致列错误了
            for (int i = 0; i < (int)AceColumnType.Count; i++)
                appConfig.MainForm.ListViewEntryColumns.Add(new AceColumn((AceColumnType)i, string.Empty, 80));
            //插件
            appConfig.Plugins.AutoRun.Add("WebMoney");

            System.Diagnostics.Process.Start(AppDefines.declare);
        }

        /// <summary>
        /// 显示提示窗体
        /// </summary>
        /// <param name="text"></param>
        public static void ShowPromptForm(System.ComponentModel.IContainer container, Control promptControl, string prompText)
        {
            if (!appConfig.App.DisplayThePromptForm)
                return;

            if (container == null)
                container = new System.ComponentModel.Container();

            FCNS.Controls.BallonToolTip toolTip = new FCNS.Controls.BallonToolTip(container);
            toolTip.SetToolTip(promptControl, prompText);
            //toolTip.ShowAlways = true;
            toolTip.Active = true;
        }

        private static void CleanUp()
        {
        }
        
        public static void LoadTranslation()
        {
            if (appConfig.App.Language == AppDefines.defaultLanguage)
                return;

                string str = AppDefines.languagePath + appConfig.App.Language + ".lng";
                if (File.Exists(str))
                    translation = Translate.LoadFromFile(str);
                else
                    MessageBox.Show(LanguageUtil.语言文件加载失败);
        }

        private static void LoadKMDataFormat()
        {
            kmDataFormat.Add(new DataFormatXML());
           // kmDataFormat.Add(new DataFormatCSV());
            kmDataFormat.Add(new DataFormatGDB());
        }
    }
}